package com.dadie.dorm.filter;





import com.dadie.dorm.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * ClassName: LoginFilter
 * Package: com.yang.filter
 * Description:
 *
 * @Author 杨鸿孝
 * @Create 2023/7/31 15:47
 * @Version 1.0
 */
@WebFilter(filterName = "login",urlPatterns = "/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println();

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String servletPath = request.getServletPath();
        String method = request.getParameter("method");
        if(servletPath.endsWith(".jpg")
                ||servletPath.endsWith(".png")
                ||servletPath.endsWith(".css")
                ||servletPath.endsWith(".js")
                ||servletPath.equals("/login.jsp")
                ||servletPath.equals("/verifyCode")
                ||servletPath.equals("/user") && "login".equals(method)) {
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if(user == null){
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
